/**
 *
 */
package com.ybkj.daijia.api.driver.v4;

import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.driver.Error;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.zhuan.ZhuanOrderRecordEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverLogin;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverLoginService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.zhuan.Car;
import com.ybkj.daijia.server.zhuan.CarType;
import com.ybkj.daijia.server.zhuan.Order;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author bo
 *
 */
@Controller("ZhuanProcessControllerV4")
@RequestMapping(value = "driver/api/rest/v4")
public class ZhuanProcessController {

    private static final Logger logger = LoggerFactory.getLogger(ZhuanProcessController.class);

    @Autowired
    private DriverService driverService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ZhuancheService zhuancheService;

    @Autowired
    private DriverLoginService driverLoginService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    /**
     * 补单
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "fillOrderZhuan", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport fillOrderZhuan(
        String employToken,
        String fromPlace, Double clientLongitude, Double clientLatitude,
        String clientName, String clientPhone, Long serverTimeStamp) {

        logger.debug(
            "recv employToken:{},fromPlace:{},clientLongitude:{},clientLatitude:{},clientName:{},clientPhone:{},serverTimeStamp:{}",
            employToken, fromPlace, clientLongitude, clientLatitude, clientName, clientPhone,
            serverTimeStamp);

        if (StringUtils.isBlank(employToken) || StringUtils.isBlank(fromPlace)
            || null == clientLongitude || null == clientLatitude ||
            StringUtils.isBlank(clientPhone) || null == serverTimeStamp) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        if (!driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
            if (driver.getStatus().equals(Driver.DRIVER_OFFLINE)) {
                return ResultTransport.getErrorBy(
                    new Error(ErrorConstantV4.EMPLOY_STATUS_ERROR.getCode(), "您还没有上班，不能补单"));
            } else {
                return ResultTransport.getErrorBy(
                    new Error(ErrorConstantV4.EMPLOY_STATUS_ERROR.getCode(), "有未完成的工单，暂不能补单"));
            }
        }

        if (!driver.getDriverJobType().contains(Driver.DriverJobType.zhuanche.toString())) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_IS_ZHUANCHE_ERROR);
        }

        if (null == driver.getCarId()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_HAS_NO_CAR);
        }

        Car car = zhuancheService.findCar(driver.getCarId());
        if (null == car) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_HAS_NO_CAR);
        }

        if (null == car.getCarTypeId()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.CAR_HAS_NO_CARTYPE);
        }

        CarType carType = zhuancheService.findCarType(car.getCarTypeId());
        if (null == carType) {
            return ResultTransport.getErrorBy(ErrorConstantV4.CAR_HAS_NO_CARTYPE);
        }

        try {

            Order order = new Order();

            order.setStartAddress(fromPlace);
            order.setStartLng(clientLongitude);
            order.setStartLat(clientLatitude);
            order.setPassengerName(clientName);
            order.setPassengerPhone(clientPhone.replaceAll(" ", ""));
            order.setChannelName(Order.ORDER_TYPE_BUDAN);
            order.setServerTime(new Date(serverTimeStamp));
            order.setStatus(Order.ORDER_STATUS_NEW);

            Passenger passenger = memberService.findOnePassengerByPhone(order.getPassengerPhone());

            Result<Order> result = zhuancheService.fillOrder(order, driver, carType);

            if (result.isSuccess()) {
                order = result.getResult();

                if (null == passenger) {
                    passenger = memberService.findOnePassengerByPhone(order.getPassengerPhone());
                    ReactorVo rVo = new ReactorVo();
                    rVo.setPassenger(passenger);
                    rVo.setActivityEvent(ActivityEvent.newRegister);
                    ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                    applicationEventMulticaster.multicastEvent(activityCheckEvent);
                }

                ZhuanOrderRecordEvent orderRecordEvent = new ZhuanOrderRecordEvent(order.getId());
                applicationEventMulticaster.multicastEvent(orderRecordEvent);

                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
                instance.setData(order.getId());
                return instance;
            } else {
                return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            }

        } catch (Exception e) {
            logger.error("api v4 driver fillOrderZhuan error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }


}
